﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OpenProgramUpdateSDK.Impl;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace OpenProgramUpdateSDK.Core
{
    class NewListUpdateClass
    {
        /*
        *json格式
        *
        *{
        *   "result": 200,
        *   "status": "update",
        *   "data": [{"url": "",path: ""}]
        *}
        */

        public List<dltype> TodoDwnFile;
        IUpdateChecker uc = new UpdateCkecker("0000");
        public bool is64Bit { get; private set; }
        public string project { get; set; }//ChannelName

        public NewListUpdateClass()
        {
            is64Bit = Environment.Is64BitOperatingSystem;
        }
        public bool CheckList(string server)
        {
            bool canupdateonlist = false;
            try
            {
                Netios.NetHTTP be = new Netios.NetHTTP();
                string nowVer = uc.getCopyRightCode(project);
                //System.Windows.Forms.MessageBox.Show(nowVer);
                //对64位系统的特殊处理
                string url = server + "/version/index/getupdatelist/soft/"+ project + "/id/" + nowVer;
                if (is64Bit)
                {
                    DialogResult rs = MessageBox.Show("检测到你正在使用64位的操作系统，需要下载对应的更新吗？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (rs == DialogResult.Yes)
                    {
                        url = server + "/version/index/getupdatelist/soft/"+ project + "_x64/id/" + nowVer;
                    }
                }
                string jsonp = be.pub_doGET(url, Encoding.UTF8);
                JObject acd = (JObject)JsonConvert.DeserializeObject(jsonp);
                if (acd["result"].ToString() == "200")
                {
                    if (acd["status"].ToString() == "update" || acd["status"].ToString() == "patch")
                    {
                        canupdateonlist = true;
                        TodoDwnFile = new List<dltype>();
                        foreach (JObject item in acd["data"])
                        {
                            dltype dlitem = JsonConvert.DeserializeObject<dltype>(item.ToString());
                            //dltype dlitem = item.ToObject<dltype>();
                            TodoDwnFile.Add(dlitem);
                        }
                    }
                }
            }
            catch (System.Exception)
            {
                canupdateonlist = false;
            }
            return canupdateonlist;
        }
    }
    public class dltype
    {
        public string url { get; set; }
        public string path { get; set; }
    }
}
